package sbc.util;

import org.xvsm.api.core.Capi;
import org.xvsm.api.core.ContainerRef;
import org.xvsm.api.core.CoordinationTypes;
import org.xvsm.client.exception.XVSMClientException;
import org.xvsm.ms.exceptions.FatalException;
import org.xvsm.ms.exceptions.UnknownContainerNameException;

public class Util {
	/**
	 * Creates of returns a named container.
	 * 
	 * @param capi
	 *            the Capi to use.
	 * @param cname
	 *            the name of the container to look for or to create.
	 * @param baseCoordType
	 *            the base coordination type of the NEW container. This argument
	 *            is only used if a new container is created. It will be ignored
	 *            if a container with cname already exists.
	 * @return the ContainerRef for a container with the name cname.
	 * @throws FatalException
	 */
	public static synchronized ContainerRef getOrCreateNamedContainer(Capi capi,
			String cname, CoordinationTypes baseCoordType)
			throws FatalException {
		try {
			System.out.println("Try to get Container: " + cname);
			ContainerRef cref = capi.getNamedContainer(cname);
			System.out.println("Container: " + cname + " already exists.");
			return cref;
		} catch (XVSMClientException e) {
			try {
				System.out.println("Try to create Container: " + cname);
				return capi.createNamedContainer(cname, baseCoordType);
			} catch (Exception e1) {
				throw new RuntimeException(e1);
			}
		} catch (UnknownContainerNameException e) {
			try {
				System.out.println("Try to create Container: " + cname);
				return capi.createNamedContainer(cname, baseCoordType);
			} catch (Exception e1) {
				throw new RuntimeException(e1);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
